package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceIml implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO incomeReport(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();
        LocalDate currentDate = begin;
        while (!currentDate.isAfter(end)) {
            dateList.add(currentDate);
            currentDate = currentDate.plusDays(1);
        }
        List<Double> turnoverList = new ArrayList<>();
        for(LocalDate date : dateList) {
            LocalDateTime beginDateTime = date.atTime(0, 0, 0);
            LocalDateTime endDateTime = date.atTime(23, 59, 59);
            Map map = new HashMap();
            map.put("beginDateTime", beginDateTime);
            map.put("endDateTime", endDateTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.getTurnover(map);
            turnoverList.add(turnover);
        }
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO userReport(LocalDate begin, LocalDate end) {
       List<LocalDate> dateList = new ArrayList<>();
        LocalDate currentDate = begin;
        while (!currentDate.isAfter(end)) {
            dateList.add(currentDate);
            currentDate = currentDate.plusDays(1);
        }
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for(LocalDate date : dateList) {
            LocalDateTime beginDateTime = date.atTime(0, 0, 0);
            LocalDateTime endDateTime = date.atTime(23, 59, 59);
            Map map = new HashMap();
            map.put("endDateTime", endDateTime);
            Integer totalUser = userMapper.countByTime(map);
            totalUserList.add(totalUser);
            map.put("beginDateTime", beginDateTime);
            Integer newUser = userMapper.countByTime(map);
            newUserList.add(newUser);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO orderReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate currentDate = begin;
        while (!currentDate.isAfter(end)) {
            dateList.add(currentDate);
            currentDate = currentDate.plusDays(1);
        }
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for(LocalDate date : dateList) {
            LocalDateTime beginDateTime = date.atTime(0, 0, 0);
            LocalDateTime endDateTime = date.atTime(23, 59, 59);
            Map map = new HashMap();
            map.put("beginDateTime", beginDateTime);
            map.put("endDateTime", endDateTime);
            Integer orderCount = orderMapper.countMap(map);
            orderCountList.add(orderCount);
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countMap(map);
            validOrderCountList.add(validOrderCount);
        }
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(orderCountList.stream().mapToInt(Integer::intValue).sum())
                .validOrderCount(validOrderCountList.stream().mapToInt(Integer::intValue).sum())
                .orderCompletionRate(validOrderCountList.stream().mapToInt(Integer::intValue).sum() * 1.0 / orderCountList.stream().mapToInt(Integer::intValue).sum())
                .build();
    }

    @Override
    public SalesTop10ReportVO top10Report(LocalDate begin, LocalDate end) {
        LocalDateTime beginDateTime = begin.atTime(0, 0, 0);
        LocalDateTime endDateTime = end.atTime(23, 59, 59);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getGoodsSales(beginDateTime, endDateTime);
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ","))
                .numberList(StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ","))
                .build();
    }

    @Override
    public void export(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(1);
        LocalDate end = LocalDate.now();
        LocalDateTime beginDateTime = begin.atTime(0, 0, 0);
        LocalDateTime endDateTime = end.atTime(23, 59, 59);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginDateTime, endDateTime);


        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);

            Row row = sheet.createRow(3);
            Cell cell = row.createCell(2);
            cell.setCellValue(businessDataVO.getTurnover());
            cell = row.createCell(4);
            cell.setCellValue(businessDataVO.getOrderCompletionRate());
            row.createCell(6).setCellValue(businessDataVO.getUnitPrice());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());


            for (int i = 0; i <30 ; i++) {
                LocalDate date = begin.plusDays(i);
                workspaceService.getBusinessData(date.atTime(0, 0, 0), date.atTime(23, 59, 59));
                row = sheet.getRow(i + 7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }


            ServletOutputStream os = response.getOutputStream();
            workbook.write(os);

            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
